#!/bin/bash
function uninit()
{
    echo -ne "\a"
    rm -rf $w
    echo
}
function downscale()
{
    INPUT="$1"
    SUBTITLE="$2"    
    SUBTITLE_DEL="$3"    
    OUTPUT="$4"
    TURBO="$5"
    mplayer -vc null -af volume=15.1:1 -ao pcm:fast:file=$w/snd.wav -vo null  "$INPUT" &> /dev/null &
    P1=$!
    faac -w -o $w/$OUTPUT.mp4 --obj-type LC $w/snd.wav &> /dev/null &
    P2=$!
    if [ -z "$TURBO" ] ;  then
	mencoder   ${SUBTITLE_DEL:+-subdelay "$SUBTITLE_DEL"}  ${SUBTITLE:+-sub "$SUBTITLE"} -profile $PROFILE -nosound -o $w/$OUTPUT.avi "$INPUT"
    else
	echo Root password
	sudo renice -12 -p $P2
	sudo nice -n -17 mencoder ${SUBTITLE:+-sub "$SUBTITLE"} -profile $PROFILE -nosound -o $w/OUTPUT.avi "$I"
    fi
    wait
}

if [ -n "$1" ]  ; then
    I1="$1"
    test -n "$I1" -a -f "$I1"  || { echo "give at least one parmeter - film name" ; exit 1 ; }
    S1="$2"
    O="${3:-$(basename "$1" .avi).mp4}"
    I2="$4"
    S2="$5"
else
    I1=`zenity --file-selection --title="plik z filmem"`
    if [ "-z" "$I1" ] ; then
	exit 1
    fi
    S1=`zenity --file-selection --title="napis"`
    if [ "-n" "$S1" ] ; then
	D1=`zenity --entry --title="opoznienie napisu"`
    fi
    
    I2=`zenity --file-selection --title="drugi plik z filmem"`
    if [ "-n" "$I2" ] ; then
	if [ "-n" "$S1" ] ; then
	    S2=`zenity --file-selection --title="drugi napis"`
	    if [ "-n" "$S2" ] ; then
		D2=`zenity --entry --title="opoznienie napisu drugiego"`
	    fi
	fi
    fi
    O=`zenity --entry --title="plik wyjsciowy"`
    if [ "-z" "$O" ] ; then
	exit 1
    fi
    O=$O.mp4
fi
#exit 1
echo "$I1:$S1:$I2:$S2:$O"
#exit 1

echo ${PROFILE:=k800}
trap uninit EXIT

w=$(mktemp -d)
mkfifo $w/snd.wav
downscale "$I1" "$S1" "$D1" out1
if [ -n "$I2" ] ; then
    downscale "$I2" "$S2" "$D2" out2
fi    
[ -f "$O" ] && rm "$O"
if [ -n "$I2" ] ; then
MP4Box -add $w/out1.mp4 -cat $w/out2.mp4 -add $w/out1.avi  -cat $w/out2.avi "$w/out.mp4"
else
MP4Box -add $w/out1.mp4 -add $w/out1.avi  "$w/out.mp4"
fi
if [ ${O:0:1} == "#" ] ; then
    ln -sf "$w/out.mp4" "$w/${O:1}"
    obexftp -u 0 -p "$w/${O:1}"
else
    mv -f "$w/out.mp4" $O
fi


